<?php
/**
 * 1.erp近14个月的销量报表 （2.月销售目标）(erp)
 */
namespace App\Logic\SalesReport;

use App\Models\Basics\SysICountry;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductAmazonSkuCCS;
use App\Models\Product\ProductRakutenSkuCCS;
use App\Models\SalesReport\MonthlyCTarget;
use App\Models\SalesReport\MonthlyCv;
use App\Models\SalesAmazon\SalesVolumeMonth;
use Illuminate\Support\Facades\DB;
class MonthlySalesVolume
{
    public static function init(){

        MonthlyCv::query()->truncate(); //重置品类销量（月）（近14个月）

        try{
            DB::beginTransaction();

            $amazonPlat = SysPlat::PLAT_AMAZON;
            $shopifyPlat = SysPlat::PLAT_SHOPIFY;
            $rakutenPlat = SysPlat::PLAT_RAKUTEN;

            $num = MonthlyCv::V_NUM - 1;
            $start = date('Ym',strtotime("midnight first day of -$num month"));
            $end = date('Ym');

            //amazon
            $area = [];
            ProductAmazonSkuCCS::query()
                ->orderBy('id')
                ->chunk(500, function ($items) use (&$area,$start,$end,$num,$amazonPlat){
                    foreach($items as $cc){
                        $svm = SalesVolumeMonth::query()
                            ->where('plat_id',$amazonPlat)
                            ->where('country_id',$cc->country_id)
                            ->where('classify_id',$cc->classify_id)
                            ->whereBetween('month',[$start,$end])
                            ->select('month',DB::raw('sum(volume) as volume'))
                            ->groupBy('month')
                            ->pluck('volume','month')
                            ->toArray();

                        $monthlySvTotal = [];
                        for($i = $num;$i >= 0;$i--){
                            $date = date('Ym',strtotime("midnight first day of -{$i} month"));
                            $monthlySvTotal['month'.$i] = array_key_exists($date,$svm) ? $svm[$date] : 0;
                        }
                        if(!array_key_exists($cc->country_id,$area)){
                            $area[$cc->country_id] = SysICountry::getAreaIdByCountryId($cc->country_id);
                        }
                        $monthlySvTotal['area_id'] = $area[$cc->country_id];
                        $monthlySvTotal['seller_id'] = $cc->seller_id;
                        $monthlySvTotal['month_target'] = self::getThisMonthSalesVolumeTarget($amazonPlat,$cc->country_id,$cc->classify_id,$end);
                        MonthlyCv::query()->updateOrCreate([
                            'plat_id' => $amazonPlat,
                            'country_id' => $cc->country_id,
                            'classify_id' => $cc->classify_id,
                            ],$monthlySvTotal);
                    }
                });
            sleep(2);

            //shopify
            $shopifyArea = [];
            ProductAmazonSkuCCS::query()
                ->orderBy('id')
                ->chunk(500, function ($items) use (&$shopifyArea,$start,$end,$num,$shopifyPlat){
                    foreach($items as $cc){
                        $svm = SalesVolumeMonth::query()
                            ->where('plat_id',$shopifyPlat)
                            ->where('country_id',$cc->country_id)
                            ->where('classify_id',$cc->classify_id)
                            ->whereBetween('month',[$start,$end])
                            ->select('month',DB::raw('sum(volume) as volume'))
                            ->groupBy('month')
                            ->pluck('volume','month')
                            ->toArray();

                        $monthlySvTotal = [];
                        for($i = $num;$i >= 0;$i--){
                            $date = date('Ym',strtotime("midnight first day of -{$i} month"));
                            $monthlySvTotal['month'.$i] = array_key_exists($date,$svm) ? $svm[$date] : 0;
                        }
                        if(!array_key_exists($cc->country_id,$shopifyArea)){
                            $shopifyArea[$cc->country_id] = SysICountry::getAreaIdByCountryId($cc->country_id);
                        }
                        $monthlySvTotal['area_id'] = $shopifyArea[$cc->country_id];
                        $monthlySvTotal['seller_id'] = $cc->seller_id;
                        $monthlySvTotal['month_target'] = self::getThisMonthSalesVolumeTarget($shopifyPlat,$cc->country_id,$cc->classify_id,$end);
                        MonthlyCv::query()->updateOrCreate([
                            'plat_id' => $shopifyPlat,
                            'country_id' => $cc->country_id,
                            'classify_id' => $cc->classify_id,
                        ],$monthlySvTotal);
                    }
                });
            sleep(2);

            //rakuten
            $rakutenArea = [];
            ProductRakutenSkuCCS::query()
                ->orderBy('id')
                ->chunk(500, function ($items) use (&$rakutenArea,$start,$end,$num,$rakutenPlat){
                    foreach($items as $cc){
                        $svm = SalesVolumeMonth::query()
                            ->where('plat_id',$rakutenPlat)
                            ->where('country_id',$cc->country_id)
                            ->where('classify_id',$cc->classify_id)
                            ->whereBetween('month',[$start,$end])
                            ->select('month',DB::raw('sum(volume) as volume'))
                            ->groupBy('month')
                            ->pluck('volume','month')
                            ->toArray();

                        $monthlySvTotal = [];
                        for($i = $num;$i >= 0;$i--){
                            $date = date('Ym',strtotime("midnight first day of -{$i} month"));
                            $monthlySvTotal['month'.$i] = array_key_exists($date,$svm) ? $svm[$date] : 0;
                        }
                        if(!array_key_exists($cc->country_id,$rakutenArea)){
                            $rakutenArea[$cc->country_id] = SysICountry::getAreaIdByCountryId($cc->country_id);
                        }
                        $monthlySvTotal['area_id'] = $rakutenArea[$cc->country_id];
                        $monthlySvTotal['seller_id'] = $cc->seller_id;
                        $monthlySvTotal['month_target'] = self::getThisMonthSalesVolumeTarget($rakutenPlat,$cc->country_id,$cc->classify_id,$end);
                        MonthlyCv::query()->updateOrCreate([
                            'plat_id' => $rakutenPlat,
                            'country_id' => $cc->country_id,
                            'classify_id' => $cc->classify_id,
                        ],$monthlySvTotal);
                    }
                });
            sleep(2);

            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    //更新目标
    protected static function getThisMonthSalesVolumeTarget($platId,$countryId,$classifyId,$month){
        $targetStartTime = MonthlyCTarget::START_DATE;
        $time = strtotime($month.'01');
        $num = getMonthDiffByDateInt(strtotime($targetStartTime),$time);
        $ytt = MonthlyCTarget::query()
            ->where('monthly',$targetStartTime)
            ->where('plat_id',$platId)
            ->where('country_id',$countryId)
            ->where('classify_id',$classifyId)
            ->first();
        return $ytt->{'estimate_volume'.$num} ?? 0;
    }

    //更新月目标（当月）(msv:up-target)
    public static function upTarget(){
        //try{
            $date = date('Ym');
            //DB::beginTransaction();
            MonthlyCv::query()
                ->orderBy('id')
                ->chunk(200, function ($items) use ($date){
                    foreach($items as $item){
                        $item->month_target = self::getThisMonthSalesVolumeTarget($item->plat_id,$item->country_id,$item->classify_id,$date);
                        $item->save();
                    }
                });
            //DB::commit();
        //}catch (\Exception $e){
        //    DB::rollBack();
        //    report($e);
        //}
    }
}
